﻿using System;
using System.Data.SqlClient;
using System.Collections.Generic;
using LitJson;
using TeleVoyeur;

// MODO SIMPLE pequeño ejemplo:
// http://televoyeur.com/updater.aspx?modo=0&descr=ale&lat=-32.9673&lon=-60.64726&vel=9.5&bea=356.3

// MODO JSON pequeño ejemplo:
// http://televoyeur.com/updater.aspx?modo=1&text={"ovnis":[{"tmp":"123456","key":"a28146297","lat":"32.32423","lon":"60.31233","vel":"2.97"},{"tmp":"123457","key":"b28146297","lat":"32.32423","lon":"60.31233","vel":"2.97"},{"tmp":"123458","key":"c28146297","lat":"32.32423","lon":"60.31233","vel":"2.97","bea":"350.6"}]}

public partial class Updater : System.Web.UI.Page
{
    protected void Page_Load (object sender, EventArgs e)
    {
        bool esGet = Request.RequestType.CompareTo("GET") == 0;

        int     modo = int.Parse(esGet ? Request.QueryString["modo"] : Request.Form["modo"]);
        string  text = (esGet ? Request.QueryString["text"] : Request.Form["text"]);

        switch (modo)
        {
            case 0: modoSimpleGet   (); break;
            case 1: modoJson        (text); break;
        }
    }
 
    public void modoSimpleGet ()
    {
        using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=w1701119_televoyeurdb;Integrated Security=SSPI;"))
        {
            try
            {
                conn.Open ();
                string ret = upsertar (conn, DateHelper.dateTime2FechaUNIX(DateTime.Now).ToString(), Request.QueryString["descr"], Request.QueryString["lat"], Request.QueryString["lon"], Request.QueryString["vel"], Request.QueryString["bea"]);
                Response.Write (ret);
            }
            catch (Exception exx)
            {
                Response.Write(exx.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }

    public void modoJson (string textoJson)
    {
        using (SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=w1701119_televoyeurdb;Integrated Security=SSPI;"))
        {
            try
            {
                GrupoOvnis  grupoOvnis  = JsonMapper.ToObject<GrupoOvnis>(textoJson);
                conn.Open   ();

                Dictionary<string, Ovni> objRespuesta= new Dictionary<string, Ovni>();
                
                foreach (Ovni ovni in grupoOvnis.ovnis)
                {
                    string retUpsert = upsertar (conn, ovni.tmp, ovni.key, ovni.lat, ovni.lon, ovni.vel, ovni.bea);
                
                    if (retUpsert.StartsWith("UPDATE") || retUpsert.StartsWith("INSERT"))
                        objRespuesta.Add (ovni.key, ovni);
                }

                Response.Write (JsonMapper.ToJson(objRespuesta));
            }
            catch (Exception exx)
            {
                Response.Write("ERROR -> ");
                Response.Write(exx.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }

    public string upsertar (SqlConnection conn, string tmp, string key, string lat, string lon, string vel, string bea)
    {
        try
        {
            string  sqlUpdate   = "update ovnis set tiempo=[TMP], lat=[LAT], lon=[LON], vel=[VEL], bea=[BEA] where descr like '[KEY]'";
            sqlUpdate = sqlUpdate.Replace("[TMP]", tmp);
            sqlUpdate = sqlUpdate.Replace("[KEY]", key);
            sqlUpdate = sqlUpdate.Replace("[LAT]", lat);
            sqlUpdate = sqlUpdate.Replace("[LON]", lon);
            sqlUpdate = sqlUpdate.Replace("[VEL]", vel);
            sqlUpdate = sqlUpdate.Replace("[BEA]", bea);
            SqlCommand cmdUpdate = new SqlCommand(sqlUpdate, conn);

            if (1 == cmdUpdate.ExecuteNonQuery())
            {
                return "UPDATE -> " + key;
            }
            else
            {
                string sqlInsert = "insert into ovnis (tiempo, descr, lat, lon, vel, bea) values ([TMP], '[KEY]', [LAT], [LON], [VEL], [BEA])";
                sqlInsert = sqlInsert.Replace("[TMP]", tmp);
                sqlInsert = sqlInsert.Replace("[KEY]", key);
                sqlInsert = sqlInsert.Replace("[LAT]", lat);
                sqlInsert = sqlInsert.Replace("[LON]", lon);
                sqlInsert = sqlInsert.Replace("[VEL]", vel);
                sqlInsert = sqlInsert.Replace("[BEA]", bea);
                SqlCommand cmdInsert = new SqlCommand(sqlInsert, conn);
                cmdInsert.ExecuteNonQuery();
                return "INSERT -> " + key;
            }
        }
        catch (Exception exx)
        {
            return "ERROR -> " + key + " -> " + exx.ToString();
        }
    }
}
